﻿using System;
using System.Collections.Generic;
using wojilu.Apps.Qycms.Domain;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class LanguageController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public LanguageController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void LanguageList()
        {
            SetPublic();
            setpublic();
            set("isalong", 0);
            set("load", to(new AdminController().Load) + "?");
            var condition = String.Empty;
            DataPage<Lng> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var isopen = ctx.GetInt("isopen");
            switch (isopen)
            {
                case 1:
                    condition += " isopen = 1 ";
                    break;

                case 2:
                    condition += " isopen = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Lng.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void LanguageAdd()
        {
            SetPublic();
            setpublic();
            target(LanguageAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("codedb", to(Codedb));
            set("tab", ctx.Get("tab") == null || ctx.Get("tab").IsNullOrEmpty() ? "false" : "true");
        }

        [HttpPost]
        public virtual void LanguageAddDo()
        {
            Lng l = new Lng();
            l.pid = cvt.ToInt(db.RunScalar("select max(pid) from ybb_lng")) + 1;
            l.lng = ctx.Post("lng");
            l.lngtitle = ctx.Post("lngtitle");
            l.url = ctx.Post("url");
            l.lockin = 1;
            l.iswap = ctx.PostInt("iswap");
            l.isopen = 0;
            l.isuptype = 0;
            l.ispack = ctx.PostInt("ispack");
            l.packname = ctx.Post("packname");
            Result result = l.insert();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("language_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("language_add_log") + lang("log_extra_ok"), "{Id:" + l.Id + ", Name:'" + l.lngtitle + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost, HttpDelete]
        public virtual void LanguageDel()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Lng>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("language_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("menulink_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void LanguageSort()
        {
            var infoid = ctx.PostIdList("infoid");
            var pid = ctx.PostIdList("pid");
            var strArray = infoid.Split(new char[] { ',' });
            var strArray1 = pid.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                string condition = string.Format("Id = {0}", strArray[i]);
                db.updateBatch<Lng>("set pid=" + strArray1[i], condition);
            }
            logService.Add((User)ctx.viewer.obj, lang("language_log_sort") + lang("log_extra_ok"), "{Id:" + infoid + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        public virtual void LanaguageSetting()
        {
            var dbname = ctx.Post("dbname");
            var value = ctx.Post("value");
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            db.updateBatch<Lng>(dbname + "=" + value, condition);
            if (ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("menulink_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("language_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LanaguageEdit(Int64 id)
        {
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("codedb", to(Codedb));
            target(LanaguageEditDo, id);
            Lng lng = Lng.findById(id);
            bind("lngread", lng);
        }

        [HttpPost]
        public virtual void LanaguageEditDo(Int64 id)
        {
            Lng l = Lng.findById(id);
            l.ispack = ctx.PostInt("ispackedit");
            l.packname = ctx.Post("packnameedit");
            l.lngtitle = ctx.Post("lngtitle");
            l.url = ctx.Post("url");
            l.iswap = ctx.PostInt("iswap");
            Result result = l.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("language_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("language_edit_log") + lang("log_extra_ok"), "{Id:" + l.Id + ", Name:'" + l.lngtitle + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LanguageCopy(Int64 id)
        {
            Lng l = Lng.findById(id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            target(LanguageCopyDo, id);
            bind("lngread", l);
            var list = Lng.find(" isuptype=0 and isopen=1 order by pid asc").list();
            bind("lnglist", list);
        }

        [HttpPost]
        public virtual void LanguageCopyDo(Int64 id)
        {
            var tolng = ctx.Post("tolng");
            Lng lng = Lng.findById(id);
            List<Lngpack> l = Lngpack.find(" lng=:l").set("l", lng.lng).list();
            foreach (var row in l)
            {
                if (!Exists(row.keycode, tolng))
                {
                    row.lng = tolng;
                    row.insert();
                }
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LngPackCopySms(Int64 id)
        {
            Lng l = Lng.findById(id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            target(LngPackCopySmsDo, id);
            bind("lngread", l);
            var list = Lng.find(" isuptype=0 and isopen=1 order by pid asc").list();
            bind("lnglist", list);
        }

        [HttpPost]
        public virtual void LngPackCopySmsDo(Int64 id)
        {
            var tolng = ctx.Post("tolng");
            Lng lng = Lng.findById(id);
            List<wojilu.Apps.Qycms.Domain.Templates> l = wojilu.Apps.Qycms.Domain.Templates.find(" lng=:l and styleclass=:s").set("l", lng.lng).set("s", 4).list();
            foreach (var row in l)
            {
                if (!TemExists(row.templatecode, tolng))
                {
                    row.lng = tolng;
                    row.insert();
                }
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LngPackCopyMail(Int64 id)
        {
            target(LngPackCopyMailDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            Lng l = Lng.findById(id);
            bind("lngread", l);
            var list = Lng.find(" isuptype=0 and isopen=1 order by pid asc").list();
            bind("lnglist", list);
        }

        [HttpPost]
        public virtual void LngPackCopyMailDo(Int64 id)
        {
            var tolng = ctx.Post("tolng");
            Lng lng = Lng.findById(id);
            List<wojilu.Apps.Qycms.Domain.Templates> l = wojilu.Apps.Qycms.Domain.Templates.find(" lng=:l and styleclass=:s").set("l", lng.lng).set("s", 3).list();
            foreach (var row in l)
            {
                if (!TemExists(row.templatecode, tolng))
                {
                    row.lng = tolng;
                    row.insert();
                }
            }
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void LngPackList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            var condition = "lng='" + DefaultLng + "'";
            DataPage<Lngpack> list = null;
            var typeid = ctx.GetInt("typeid");
            var lockin = ctx.GetInt("lockin");
            var maxperpage = ctx.PostInt("MaxPerPage");
            var page_id = ctx.PostInt("page_id") + 1;
            var limitkey = ctx.Get("limitkey");
            var limitclass = ctx.Get("limitclass");
            if (typeid != 0)
            {
                condition += " and typeid=" + typeid;
            }
            switch (lockin)
            {
                case 1:
                    condition += " and lockin = 1 ";
                    break;

                case 2:
                    condition += " and lockin = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "asc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Lngpack.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void LanPackAdd()
        {
            target(LanPackAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("lanpackcodedb", to(LanPackCodedb));
            set("tab", ctx.Get("tab") == null || ctx.Get("tab").IsNullOrEmpty() ? "false" : "true");
            var lng = DefaultLng;
            set("lng", lng);
            var lanpacklist = cdb.findAll<LanPackType>();
            bind("lanpacklist", lanpacklist);

        }

        [HttpPost]
        public virtual void LanPackAddDo()
        {
            Lngpack l = new Lngpack();
            l.typeid = ctx.PostInt("typeid");
            l.lng = ctx.Post("lng");
            l.pid = 50;
            l.title = ctx.Post("title");
            l.keycode = ctx.Post("keycode");
            l.langstr = ctx.PostHtmlAll("langstr");
            l.lockin = 0;
            Result result = l.insert();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_add_log") + lang("log_extra_ok"), "{Id:" + l.Id + ", Name:'" + l.title + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void LanPackDel()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Lngpack>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void LanPackEdit(Int64 id)
        {
            target(LanPackEditDo, id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("lanpackcodedb", to(LanPackCodedb));
            var lng = DefaultLng;
            set("lng", lng);
            Lngpack l = Lngpack.findById(id);
            bind("read", l);
            var lanpacklist = cdb.findAll<LanPackType>();
            bind("lanpacklist", lanpacklist);
        }

        [HttpPost]
        public virtual void LanPackEditDo(Int64 id)
        {
            Lngpack l = Lngpack.findById(id);
            l.typeid = ctx.PostInt("typeid");
            l.title = ctx.Post("title");
            l.langstr = ctx.PostHtmlAll("langstr");
            Result result = l.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("languagepack_edit_log") + lang("log_extra_ok"), "{Id:" + l.Id + ", Name:'" + l.title + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
        }

        [HttpPost]
        public virtual void LanPackCodedb()
        {
            var lng = ctx.Post("lng");
            var codename = ctx.Post("codename");
            var count = Lngpack.count(" keycode='" + codename + "' and lng='" + lng + "'");
            if (count > 0)
            {
                ctx.web.ResponseWrite("false");
            }
            else
            {
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void Codedb()
        {
            var ispack = ctx.PostInt("ispack");
            if (ispack == 1)
            {
                ctx.web.ResponseWrite(ExistLng(ctx.Post("packname")));
            }
            else
            {
                ctx.web.ResponseWrite(ExistLng(ctx.Post("codename")));
            }
            ctx.web.ResponseEnd();
        }

        public String ExistLng(String name)
        {
            var i = Lng.count(" lng == '" + name + "'");
            if (i > 0) return "false";
            return "true";
        }

        protected Boolean Exists(String keycode, String lng)
        {
            return Lngpack.find("keycode=:k and lng=:l").set("k", keycode).set("l", lng).list().Count > 0;
        }

        protected Boolean TemExists(String templatecode, String lng)
        {
            return wojilu.Apps.Qycms.Domain.Templates.find("templatecode=:t and lng=:l").set("t", templatecode).set("l", lng).list().Count > 0;
        }

    }
}